var express = require('express')
var ws = require('nodejs-websocket')
var tool = require('./tool')

//客户端集合
var clientMap = {}

//websocket服务器
var server = ws.createServer(function (conn) {
    conn.on('text', function (str) {
        try {
            var data = JSON.parse(str)
        }catch (e) {
            console.log("解析数据异常", e)
            return
        }

        var user = clientMap[conn.key]
        if (!user) {
            console.log('用户找不到', user)
            return
        }

        progressReceiveMessage(conn.key, user.userName, data)
    })

    conn.on('close', function () {
        // console.log('断开连接')
        var key = conn.key
        var user = clientMap[key]
        if(!user) {
            return
        }
        var userName = user.userName
        console.log('用户[' + userName + ']断开连接')

        delete clientMap[key]
    })

    conn.on('error', function () {
        // console.log('发生异常')
        //客户端发生，从集合中去除
        var key = conn.key
        var user = clientMap[key]
        if(!user) {
            return
        }
        var userName = user.userName
        console.log('用户[' + userName + ']异常关闭')

        delete clientMap[key]
    })
})

server.on('connection', function (conn) {
    //获取用户名
    var query = tool.query(conn.path)
    var userName = query.userName
    if (!userName) {
        console.log('没有用户名，断开连接')
        return
    }

    //用户信息
    var user = {
        userName: userName,
        conn: conn
    }

    //获取uuid
    // var uuid = tool.uuid()
    //以conn.key作为用户标识
    var key = conn.key
    clientMap[key] = user

    console.log('当前用户数：', tool.getJsonLength(clientMap))
    //向新用户发送用户信息
    singleSend(conn, {
        command: 'returnUserInfo',
        userName: userName,
        userKey: key
    })
    //通知所有客户端有新用户登录
    groupSend(clientMap, {
        command: 'userInto',
        userKey: key,
        msg: '欢迎用户[' + user.userName + ']加入'
    })
})

server.listen(8001, function () {
    console.log('websocket服务器启动')
})

//http服务器
var app = express()

app.get('/', function(req, resp) {
    resp.send('123')
})

app.use('/', express.static('./static/'))

app.listen(8081, function () {
    console.log('http服务器启动')
})

//单发
function singleSend(client, msg) {
    msg = progressSendMsg(msg)
    client.send(msg)
}

//群发
function groupSend(clientMap, msg) {
    msg = progressSendMsg(msg)
    for (var key in clientMap) {
        var user = clientMap[key]
        user.conn.send(msg)
    }
}

//处理发送消息
function progressSendMsg(msg) {
    if (typeof msg != 'string') {
        msg = JSON.stringify(msg)
    }
    return msg
}

//处理接收的消息
function progressReceiveMessage(userKey, userName, data) {
    var command = data.command
    switch (command) {
        case "message":
            progressPlainText(userKey, userName, data.msg)
            break
        default:
            console.log("未知的命令：", command)
    }
}

//处理普通文本信息
function progressPlainText(userKey, userName, msg) {
    //群发
    groupSend(clientMap, {
        command: 'message',
        userKey: userKey,
        userName: userName,
        msg: msg
    })
}